﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.ExpertGroups;
using YAPACS.Organizations;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Study;

public class ApplyConsultation(IRepository<DepartmentExpertGroup, Guid> departmentExpertGroupRepository, ICurrentUserOrganization currentUserOrganization,
    IConsultation consultation)
    : WorkflowBase, IApplyConsultation, ITransientDependency
{
    private readonly IRepository<DepartmentExpertGroup, Guid> _departmentExpertGroupRepository = departmentExpertGroupRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IConsultation _consultation = consultation;
    protected async override Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        const string key = "Exams";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is List<Exam> exams)
        {
            foreach (var exam in exams)
            {
                if (exam.ExamStatus == ExamStatus.Completed || (exam.Report != null && exam.Report.ReportStatus == ReportStatus.Completed))
                {
                    throw new Exception($"患者【{exam.Patient.Name}({exam.AccessionNumber})】的检查已完成，不能申请会诊");
                }
            }
            WorkflowOutput workflowOutput = new() { Success = true };
            var query = await _departmentExpertGroupRepository.GetQueryableAsync();
            query = query.Where(e => e.Department.Oid == _currentUserOrganization.DepartmentId && e.ExpertGroup.IsActive).OrderBy(e => e.ExpertGroup.Order).ThenBy(e => e.ExpertGroup.Name);
            var list = await AsyncExecuter.ToListAsync(query.Select(e => new
            {
                Label = e.ExpertGroup.Name,
                Value = e.ExpertGroup.Oid
            }));
            if (list.Count == 0)
            {
                throw new Exception("科室未设置专家组");
            }
            // 手动选择专家组
            if (list.Count > 1 || (exams.Count == 1 && exams[0].ExpertGroup != null))
            {
                var department = exams.Select(e => e.Department).Distinct().First();
                workflowOutput.View = await Extensions.GetResourceStringAsync("Resources.Study.apply-consultation.json");
                Guid? defaultExpertGroupId = null;
                if (exams.Count == 1)
                {
                    defaultExpertGroupId = exams[0].ExpertGroup?.Oid;
                }
                if (defaultExpertGroupId == null)
                {
                    var defaultExpertGroup = department.GetExpertGroup();
                    defaultExpertGroupId = defaultExpertGroup?.Oid;
                }
                workflowOutput.Data = new
                {
                    ExpertGroup = defaultExpertGroupId
                };
                workflowOutput.Content = new { ExpertGroups = list };
                workflowOutput.ViewTitle = "申请会诊";
                workflowOutput.NextAction = "会诊-会诊";
                workflowOutput.ViewWidth = "35%";
            }
            //自动选择专家组
            else
            {
                var expertGroupId = list[0].Value;
                workflowOutput = await _consultation.InvokeAsync(new WorkflowInput
                {
                    {
                        "Input",new Dictionary<string, object>
                        {
                            { "expertGroup", expertGroupId.ToString() },
                            { "examIds", exams.Select(e=>e.Oid) }
                        }
                    }
                });
            }
            //处理逻辑
            return workflowOutput;
        }

        return new WorkflowOutput
        {
            Success = false,
            Error = "未找到Exam对象",
        };
    }
}
